<template>
	<div class="pound-container">
		<div class="pound-bottom">
			<el-card>
				<template #header>
					<div style="display: flex;justify-content: space-between;">
						<div class="card-header" style="font-size: 24px;font-weight: 550;">
							<span>地磅历史数据</span>
						</div>
						<div>
							<!-- 修正：删除重复的placement属性 -->
							<el-tooltip content="导出数据" placement="bottom-end">
								<el-button :icon="Bottom" size="default" @click="handleExportOpen" type="text"
									style="font-size: 28px; padding: 0; color: #000;" hover-class="el-button--hover">
								</el-button>
							</el-tooltip>
						</div>
					</div>
				</template>

				<!-- 查询表单 -->
				<el-form :inline="true" :model="formInline" class="demo-form-inline">
					<el-form-item label="过磅时间">
						<el-date-picker v-model="formInline.weighingDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
							type="date" placeholder="请选择过磅时间" style="width: 120px" />
					</el-form-item>
					<el-form-item label="车牌号">
						<el-input v-model="formInline.autoLicense" placeholder="请输入车牌号" clearable
							style="width: 120px" />
					</el-form-item>
					<el-form-item label="货物名称">
						<el-input v-model="formInline.cargoName" placeholder="请输入货物名称" clearable style="width: 120px" />
					</el-form-item>
					<el-form-item label="发货单位">
						<el-select v-model="formInline.shippingCompanyId" placeholder="请选择发货单位" style="width: 140px"
							clearable>
							<el-option v-for="item in caiOptions" :key="item.id" :label="item.companyName"
								:value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="收货单位">
						<el-select v-model="formInline.receivingCompanyId" placeholder="请选择收货单位" style="width: 140px"
							clearable>
							<el-option v-for="item in xiaoOptions" :key="item.id" :label="item.companyName"
								:value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="过磅状态">
						<el-select v-model="formInline.weightStatus" placeholder="请选择过磅状态" style="width: 140px"
							clearable>
							<el-option v-for="item in options" :key="item.value" :label="item.label"
								:value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="onSubmit">查 询</el-button>
						<el-button type="default" @click="handleReset" style="margin-left: 8px;">重 置</el-button>
					</el-form-item>
				</el-form>

				<!-- 数据表格 -->
				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="time" label="时间" width="140">
						<template #default="{row}"><span>{{ row.updateTime ||'-'}}</span></template>
					</el-table-column>
					<el-table-column prop="autoLicense" label="车牌号" width="120">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.autoLicense" />
							<span v-else>{{ row.autoLicense ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column label="集装箱号" width="120">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.containerNum" />
							<span v-else>{{ row.containerNum ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="cargoName" label="货物名称" width="140">
						<template #default="{row}">
							<el-select v-if="row.isEditing" v-model="row.deductingId" filterable default-first-option
								:reserve-keyword="false" placeholder="请输入或选择货名" style="width: 100%" clearable
								@change="handleCargoChange(row, $event)">
								<el-option v-for="item in cargoOptions" :key="item.id" :label="item.cargoName"
									:value="item.id">
									<span>{{ item.cargoName }}</span>
								</el-option>
							</el-select>
							<span v-else>{{ row.cargoName ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="shippingCompany" label="发货厂家" width="140">
						<template #default="{row}">
							<el-select v-if="row.isEditing" v-model="row.shippingCompanyId" filterable
								:reserve-keyword="false" placeholder="请选择发货厂家" style="width: 120px" value-key="id"
								@change="handleCompanyChange(row, 'shipping')">
								<el-option v-for="item in caiOptions" :key="item.id" :label="item.companyName"
									:value="item.id"><span>{{ item.companyName }}</span></el-option>
							</el-select>
							<span v-else>{{ row.shippingCompany ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="receivingCompany" label="收货厂家" width="140">
						<template #default="{row}">
							<el-select v-if="row.isEditing" v-model="row.receivingCompanyId" filterable
								:reserve-keyword="false" placeholder="请选择收货厂家" style="width: 120px" value-key="id"
								@change="handleCompanyChange(row, 'receiving')">
								<el-option v-for="item in xiaoOptions" :key="item.id" :label="item.companyName"
									:value="item.id"><span>{{ item.companyName }}</span></el-option>
							</el-select>
							<span v-else>{{ row.receivingCompany ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="roughWeight" label="毛重" width="120">
						<template #default="{ row }">
							<el-tooltip class="box-item" effect="dark" content="输入完成回车重新计算" placement="top-start"
								v-if="row.isEditing&&row.weightStatus!=1">
								<el-input type="text" v-model="row.roughWeight" placeholder="请输入毛重（如20.05）" @input="(val) => {
									const validVal = val.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace(/^\./, '');
									const decimalIndex = validVal.indexOf('.');
									const filteredVal = decimalIndex !== -1 ? validVal.slice(0, decimalIndex + 3) : validVal;
									row.roughWeight = filteredVal; 
								}" @blur="() => {
									const numVal = row.roughWeight === '' ? 0 : Number(row.roughWeight);
									row.roughWeight = Number(numVal.toFixed(2)); 
									calculateSuttle(row); 
								}" @keyup.enter="() => {
									const numVal = row.roughWeight === '' ? 0 : Number(row.roughWeight);
									row.roughWeight = Number(numVal.toFixed(2));
									calculateSuttle(row);
								}" />
							</el-tooltip>
							<span
								v-else>{{row.roughWeight === undefined || row.roughWeight === null|| row.roughWeight === 0 ? '-' : row.roughWeight }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="tare" label="皮重" width="120">
						<template #default="{ row }">
							<el-tooltip class="box-item" effect="dark" content="输入完成回车重新计算" placement="top-start"
								v-if="row.isEditing&&row.weightStatus!=1">
								<el-input type="text" v-model="row.tare" placeholder="请输入皮重（如31.04）" @input="(val) => {
									const validVal = val.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace(/^\./, '');
									const decimalIndex = validVal.indexOf('.');
									const filteredVal = decimalIndex !== -1 ? validVal.slice(0, decimalIndex + 3) : validVal;
									row.tare = filteredVal; 
								}" @blur="() => {
									const numVal = row.tare === '' ? 0 : Number(row.tare);
									row.tare = Number(numVal.toFixed(2));
									calculateSuttle(row);
								}" @keyup.enter="() => {
									const numVal = row.tare === '' ? 0 : Number(row.tare);
									row.tare = Number(numVal.toFixed(2));
									calculateSuttle(row);
								}" />
							</el-tooltip>
							<span
								v-else>{{ row.tare === undefined || row.tare === null|| row.tare === 0 ? '-' : row.tare}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="suttle" label="净重" width="120">
						<template #default="{row}">
							<el-input v-if="row.isEditing&&row.weightStatus!=1" v-model="row.suttle" disabled />
							<span
								v-else>{{row.suttle === undefined || row.suttle === null|| row.suttle === 0 ? '-' : row.suttle}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="settlementSuttle" label="结算净重" width="120">
						<template #default="{row}">
							<el-input v-if="row.isEditing&&row.weightStatus!=1" v-model="row.settlementSuttle"
								disabled />
							<span
								v-else>{{ row.settlementSuttle === undefined || row.settlementSuttle === null|| row.settlementSuttle === 0 ? '-' : row.settlementSuttle}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="specifications" label="规格" width="100">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.specifications" />
							<span v-else>{{ row.specifications ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="driverName" label="司机姓名" width="90">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.driverName" />
							<span v-else>{{ row.driverName ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="weigher" label="司磅员" width="90">
						<template #default="{row}">
							<el-input v-if="row.isEditing" v-model="row.weigher" />
							<span v-else>{{ row.weigher ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="reviewer" label="审核员" width="90">
						<template #default="{row}">
							<span>{{ row.reviewer ||'-'}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="weighingType" label="过磅类型" width="90">
						<template #default="{row}"><span>{{ row.weighingType === 1 ? '采购' : '销售' }}</span></template>
					</el-table-column>
					<el-table-column prop="isAdditionalRecording" label="是否补录" width="90">
						<template #default="{row}"><span>{{row.isAdditionalRecording=== 1?'是':'否'}}</span></template>
					</el-table-column>
					<el-table-column prop="weightStatus" label="状态" width="160">
						<template #default="{row}"><span>{{ getStatusText(row.weightStatus)  ||'-'}}</span></template>
					</el-table-column>
					<el-table-column label="操作" width="290" fixed="right">
						<template #default="{row}">
							<el-button v-if="row.isEditing" type="success" size="small"
								@click="handleSave(row)">保存</el-button>
							<el-button v-if="row.isEditing" type="info" size="small"
								@click="handleCancelEdit(row)">取消</el-button>
							<el-button v-if="!row.isEditing" type="primary" size="small"
								@click="handleEdit(row)">编辑</el-button>
							<el-button v-if="row.weightStatus != 0 && !row.isEditing && row.isAdditionalRecording!=1"
								type="success" size="small" @click="handleRollback(row)">回退</el-button>
							<el-button v-if="!row.isEditing && role==='3' " type="info" size="small"
								@click="handleView(row)">查看</el-button>
							<el-button v-if="!row.isEditing && row.weightStatus===2" type="info" size="small"
								@click="handlePrint(row)">打印</el-button>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页 -->
				<div style="margin-top: 5px; display: flex;flex-direction:row-reverse;">
					<el-pagination v-if="hstotal>0" v-model:current-page="hslistQuery.current"
						v-model:page-size="hslistQuery.size" :page-sizes="[5, 8, 10]" :size="size" :background="false"
						layout="sizes, prev, pager, next" :total="hstotal" @size-change="handleSizeChange"
						@current-change="handleCurrentChange" />
				</div>
			</el-card>
		</div>
	</div>

	<!-- 详情弹窗 -->
	<el-dialog v-model="viewDialogVisible" title="详情查看" width="900px">
		<el-descriptions :column="2" border>
			<el-descriptions-item label="时间">{{ viewData?.secondAweighingTime || '-' }}</el-descriptions-item>
			<el-descriptions-item label="车牌号">{{ viewData?.autoLicense || '-' }}</el-descriptions-item>
			<el-descriptions-item label="货物名称">{{ viewData?.cargoName || '-' }}</el-descriptions-item>
			<el-descriptions-item
				label="过磅类型">{{ viewData?.weighingType === 1 ? '采购' : '销售' || '-' }}</el-descriptions-item>
			<el-descriptions-item label="原始皮重">{{ viewData?.relyTare || '-' }}</el-descriptions-item>
			<el-descriptions-item label="原始毛重">{{ viewData?.relyRoughWeight || '-' }}</el-descriptions-item>
			<el-descriptions-item label="原始净重">{{ viewData?.relySuttle || '-' }}</el-descriptions-item>
			<el-descriptions-item label="结算净重">{{ viewData?.settlementSuttle || '-' }}</el-descriptions-item>
			<el-descriptions-item label="规格">{{ viewData?.specifications || '-' }}</el-descriptions-item>
			<el-descriptions-item label="司机姓名">{{ viewData?.driverName || '-' }}</el-descriptions-item>
			<el-descriptions-item label="司磅员">{{ viewData?.weigher || '-' }}</el-descriptions-item>
			<el-descriptions-item label="状态">{{ getStatusText(viewData?.weightStatus) || '-' }}</el-descriptions-item>
		</el-descriptions>
		<template #footer>
			<div class="dialog-footer"><el-button @click="viewDialogVisible = false">关闭</el-button></div>
		</template>
	</el-dialog>

	<!-- 称重计量单弹窗 -->
	<el-dialog v-model="dialogVisible" width="900px" class="print-dialog" height="800px" :before-close="handleClose">
		<div class="template-selector" style="margin-bottom: 16px; display: flex; align-items: center;">
			<span style="margin-right: 8px; font-weight: 500;">模板选择：</span>
			<el-select v-model="selectedTemplateType" placeholder="请选择打印模板" style="width: 300px"
				@change="handleTemplateChange">
				<el-option v-for="item in templateOptions" :key="item.value" :label="item.label" :value="item.value" />
			</el-select>
		</div>


		<div class="dybox-container">
			<div class="dybox">
				<!-- 模板1：盛虹入库 -->
				<div v-if="poundTemplateType === 1" class="pound-template template1">
					<div class="header-info">
						<div style="text-align: center; font-weight: bold; font-size: 19px;">河北鸿科碳素有限公司</div>
						<div style="text-align: center; font-weight: bold; font-size: 14px;">过磅单</div>
					</div>
					<div class="header-info"
						style="font-family: SimSun, serif; display: flex; justify-content: space-between;">
						<div class="print-time">{{ editableData.nowTime }}</div>
						<div>单位：吨</div>
						<div>No. {{ editableData.weightNumber }}</div>
					</div>
					<table class="print-table" border="2" cellspacing="0" cellpadding="3"
						style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">
						<tr>
							<td style="width: 20%;">单位名称</td>
							<td colspan="4" style="width: 80%;" data-field="shippingCompany">
								{{ editableData.shippingCompany }}
							</td>
						</tr>
						<tr>
							<td>车号</td>
							<td>货物名称</td>
							<td>毛重</td>
							<td>皮重</td>
							<td>净重</td>
						</tr>
						<tr>
							<td data-field="autoLicense">{{ editableData.autoLicense }}</td>
							<td data-field="cargoName">
								<el-select v-if="isPEditing" v-model="editableData.deductingId" filterable
									default-first-option :reserve-keyword="false" placeholder="请输入或选择货名"
									style="width: 100%" clearable @change="handlePopupCargoChange">
									<el-option v-for="item in cargoOptions" :key="item.id" :label="item.cargoName"
										:value="item.id">
										<span>{{ item.cargoName }}</span>
									</el-option>
								</el-select>
								<span v-else>{{ editableData.cargoName || '' }}</span>
							</td>
							<td data-field="roughWeight">{{ editableData.roughWeight }}</td>
							<td data-field="tare">{{ editableData.tare }}</td>
							<td data-field="suttle">{{ editableData.suttle }}</td>
						</tr>
						<tr>
							<td data-field="autoLicense">{{' '}}</td>
							<td data-field="cargoName">{{' '}}</td>
							<td data-field="roughWeight">{{' '}}</td>
							<td data-field="tare">{{' '}}</td>
							<td data-field="suttle">{{' '}}</td>
						</tr>
						<tr>
							<td colspan="1">备注</td>
							<td colspan="2"></td>
							<td>司磅</td>
							<td data-field="weigher">{{ editableData.weigher }}</td>
						</tr>
					</table>
				</div>

				<!-- 模板2：盛虹出库 -->
				<div v-if="poundTemplateType === 2" class="pound-template template2">
					<div class="header-info">
						<div style="text-align: center; font-weight: bold; font-size: 22px;">过磅单</div>
					</div>
					<div class="header-info"
						style="font-family: SimSun, serif;  display: flex; justify-content: space-between;">
						<div class="print-time">{{ editableData.nowTime }}</div>
						<div>单位：吨</div>
						<div>No. {{ editableData.weightNumber }}</div>
					</div>
					<table class="print-table" border="2" cellspacing="0" cellpadding="1"
						style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">
						<tr>
							<td style="width: 20%;">单位名称</td>
							<td colspan="4" style="width: 80%;" data-field="shippingCompany">
								{{ editableData.shippingCompany }}
							</td>
						</tr>
						<tr>
							<td>车号</td>
							<td>货物名称</td>
							<td>毛重</td>
							<td>皮重</td>
							<td>净重</td>
						</tr>
						<tr>
							<td data-field="autoLicense">{{ editableData.autoLicense }}</td>
							<td data-field="cargoName">
								<el-select v-if="isPEditing" v-model="editableData.deductingId" filterable
									default-first-option :reserve-keyword="false" placeholder="请输入或选择货名"
									style="width: 100%" clearable @change="handlePopupCargoChange">
									<el-option v-for="item in cargoOptions" :key="item.id" :label="item.cargoName"
										:value="item.id">
										<span>{{ item.cargoName }}</span>
									</el-option>
								</el-select>
								<span v-else>{{ editableData.cargoName || '' }}</span>
							</td>
							<td data-field="roughWeight">{{ editableData.roughWeight }}</td>
							<td data-field="tare">{{ editableData.tare }}</td>
							<td data-field="suttle">{{ editableData.suttle }}</td>
						</tr>
						<tr>
							<td data-field="autoLicense">{{' '}}</td>
							<td data-field="cargoName">{{' '}}</td>
							<td data-field="roughWeight">{{' '}}</td>
							<td data-field="tare">{{' '}}</td>
							<td data-field="suttle">{{' '}}</td>
						</tr>
						<tr>
							<td colspan="1">备注</td>
							<td colspan="2"></td>
							<td>司磅</td>
							<td data-field="weigher">{{ editableData.weigher }}</td>
						</tr>
					</table>
				</div>

				<!-- 模板3：天津大港入库 -->
				<div v-if="poundTemplateType === 3" class="pound-template template3">
					<div class="header-info">
						<div style="text-align: center; font-weight: bold; font-size: 19px;">河北鸿科碳素有限公司</div>
						<div style="text-align: center; font-weight: bold; font-size: 14px;">入库单</div>
					</div>
					<div class="header-info"
						style="font-family: SimSun, serif;  display: flex; justify-content: space-between;">
						<div class="print-time">{{ editableData.nowTime }}</div>
						<div>单位：吨</div>
						<div>No. {{ editableData.weightNumber }}</div>
					</div>
					<table class="print-table" border="2" cellspacing="0" cellpadding="1"
						style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">
						<tr>
							<td style="width: 20%;">单位名称</td>
							<td colspan="4" style="width: 80%;" data-field="shippingCompany">
								{{ editableData.shippingCompany }}
							</td>
						</tr>
						<tr>
							<td>车号</td>
							<td>货物名称</td>
							<td>毛重</td>
							<td>皮重</td>
							<td>净重</td>
						</tr>
						<tr>
							<td data-field="autoLicense">{{ editableData.autoLicense }}</td>
							<td data-field="cargoName">
								<el-select v-if="isPEditing" v-model="editableData.deductingId" filterable
									default-first-option :reserve-keyword="false" placeholder="请输入或选择货名"
									style="width: 100%" clearable @change="handlePopupCargoChange">
									<el-option v-for="item in cargoOptions" :key="item.id" :label="item.cargoName"
										:value="item.id">
										<span>{{ item.cargoName }}</span>
									</el-option>
								</el-select>
								<span v-else>{{ editableData.cargoName || '' }}</span>
							</td>
							<td data-field="roughWeight">{{ editableData.roughWeight }}</td>
							<td data-field="tare">{{ editableData.tare }}</td>
							<td data-field="suttle">{{ editableData.suttle }}</td>
						</tr>
						<tr>
							<td data-field="autoLicense">{{' '}}</td>
							<td data-field="cargoName">{{' '}}</td>
							<td data-field="roughWeight">{{' '}}</td>
							<td data-field="tare">{{' '}}</td>
							<td data-field="suttle">{{' '}}</td>
						</tr>
						<tr>
							<td colspan="1">备注</td>
							<td colspan="2"></td>
							<td>司磅</td>
							<td data-field="weigher">{{ editableData.weigher }}</td>
						</tr>
					</table>
				</div>

				<!-- 模板4：天津大港出库 -->
				<div v-if="poundTemplateType === 4" class="pound-template template4">
					<div class="header-info">
						<div style="text-align: center; font-weight: bold; font-size: 19px;">河北鸿科碳素有限公司</div>
						<div style="text-align: center; font-weight: bold; font-size: 14px;">过磅单</div>
					</div>
					<div class="header-info"
						style="font-family: SimSun, serif;  display: flex; justify-content: space-between;">
						<div class="print-time">{{ editableData.nowTime }}</div>
						<div>单位：吨</div>
						<div>No. {{ editableData.weightNumber }}</div>
					</div>
					<table class="print-table" border="2" cellspacing="0" cellpadding="1"
						style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">
						<tr>
							<td style="width: 16%;">单位名称</td>
							<td colspan="5" style="width: 84%;" data-field="shippingCompany">
								{{ editableData.shippingCompany }}
							</td>
						</tr>
						<tr>
							<td>车号</td>
							<td>货物名称</td>
							<td>毛重</td>
							<td>皮重</td>
							<td>净重</td>
							<td>结算量</td>
						</tr>
						<tr>
							<td data-field="autoLicense">{{ editableData.autoLicense }}</td>
							<td data-field="cargoName">
								<el-select v-if="isPEditing" v-model="editableData.deductingId" filterable
									default-first-option :reserve-keyword="false" placeholder="请输入或选择货名"
									style="width: 100%" clearable @change="handlePopupCargoChange">
									<el-option v-for="item in cargoOptions" :key="item.id" :label="item.cargoName"
										:value="item.id">
										<span>{{ item.cargoName }}</span>
									</el-option>
								</el-select>
								<span v-else>{{ editableData.cargoName || ' ' }}</span>
							</td>
							<td data-field="roughWeight">{{ editableData.roughWeight }}</td>
							<td data-field="tare">{{ editableData.tare }}</td>
							<td data-field="suttle">{{ editableData.suttle }}</td>
							<td>{{ editableData.settlementSuttle }}</td>
						</tr>
						<tr>
							<td data-field="autoLicense">{{' '}}</td>
							<td data-field="cargoName">{{' '}}</td>
							<td data-field="roughWeight">{{' '}}</td>
							<td data-field="tare">{{' '}}</td>
							<td data-field="suttle">{{' '}}</td>
							<td></td>
						</tr>
						<tr>
							<td colspan="1">备注</td>
							<td colspan="2"></td>
							<td>司磅</td>
							<td colspan="2" data-field="weigher">{{ editableData.weigher }}</td>
						</tr>
					</table>
				</div>

				<!-- 模板5：针式打印机专用模板 -->
				<div v-if="poundTemplateType === 5" class="pound-template template5">
					<div class="header-info">
						<div style="text-align: center; font-weight: bold; font-size: 22px;">河北鸿科碳素有限公司</div>
						<div style="text-align: center; font-weight: bold; font-size: 14px;">称重计量单</div>
					</div>
					<div class="header-info"
						style="font-family: SimSun, serif;  display: flex; justify-content: space-between;">
						<div class="print-time">{{ editableData.nowTime }}</div>
						<div>单位：吨</div>
						<div>No. {{ editableData.weightNumber }}</div>
					</div>
					<table class="print-table" border="2" cellspacing="0" cellpadding="1"
						style="width: 100%; border-collapse: collapse; font-family: SimSun; ">
						<tr>
							<td style="width: 10%; text-align: center;">车号</td>
							<td style="width: 15%;" data-field="autoLicense">{{ editableData.autoLicense || '-' }}</td>
							<td style="width: 10%; text-align: center;">发货单位</td>
							<td colspan="5" style="width: 55%;" data-field="shippingCompany">
								{{ editableData.shippingCompany || '' }}
							</td>
						</tr>
						<tr>
							<td style="width: 10%; text-align: center;">货名</td>
							<td style="width: 15%;" data-field="cargoName">
								<el-select v-if="isPEditing" v-model="editableData.deductingId" filterable
									default-first-option :reserve-keyword="false" placeholder="请输入或选择货名"
									style="width: 100%" clearable @change="handlePopupCargoChange">
									<el-option v-for="item in cargoOptions" :key="item.id" :label="item.cargoName"
										:value="item.id">
										<span>{{ item.cargoName }}</span>
									</el-option>
								</el-select>
								<span v-else>{{ editableData.cargoName || ' ' }}</span>
							</td>
							<td style="width: 10%; text-align: center;">收货单位</td>
							<td colspan="5" style="width: 55%;" data-field="receivingCompany">
								{{ editableData.receivingCompany || '' }}
							</td>
						</tr>
						<tr>
							<td style="width: 10%; text-align: center;">毛重</td>
							<td style="width: 10%;" data-field="roughWeight">{{ editableData.roughWeight || '0.00' }}
							</td>
							<td style="width: 10%; text-align: center;">皮重</td>
							<td style="width: 10%;" data-field="tare">{{ editableData.tare || '0.00' }}</td>
							<td style="width: 15%; text-align: center;">净重</td>
							<td style="width: 15%;" data-field="suttle">
								{{ editableData.suttle !== undefined ? editableData.suttle : '0.00' }}
							</td>
							<td style="width: 15%; text-align: center;">结算净重</td>
							<td style="width: 15%;" data-field="settlementSuttle">
								{{ editableData.settlementSuttle !== undefined ? editableData.settlementSuttle : '0.00' }}
							</td>
						</tr>
						<tr>
							<td style="width: 12.5%; text-align: center;">司机</td>
							<td style="width: 12.5%;" data-field="driverName">{{ editableData.driverName || '' }}</td>
							<td style="width: 12.5%; text-align: center;">规格</td>
							<td style="width: 12.5%;" data-field="specifications">
								{{ editableData.specifications || '' }}
							</td>
							<td style="width: 12.5%; text-align: center;" colspan="2">司磅员</td>
							<td style="width: 12.5%;" data-field="weigher" colspan="2">{{ editableData.weigher || '' }}
							</td>
						</tr>
					</table>
				</div>

				<!-- 模板6：新增过磅单 -->
				<div v-if="poundTemplateType === 6" class="pound-template template6">
					<div class="header-info">
						<div v-if="editableData.weighingType===2"
							style="text-align: center; font-weight: bold; font-size: 18px;letter-spacing: 20px;">河北井陉库
						</div>
						<div v-else
							style="text-align: center; font-weight: bold; font-size: 18px;letter-spacing: 20px;">
							河北鸿科碳素有限公司</div>
						<div v-if="editableData.weighingType===2"
							style="text-align: center; font-weight: bold; font-size: 14px;letter-spacing: 12px;">出库过磅单
						</div>
						<div v-else
							style="text-align: center; font-weight: bold; font-size: 12px;letter-spacing: 12px;">入库过磅单
						</div>


					</div>
					<div class="header-info"
						style="font-family: SimSun, serif; display: flex; justify-content: space-between;">
						<div class="print-time">{{ editableData.nowTime }}</div>
						<div>单位：吨</div>
					</div>
					<table class="print-table" border="2" cellspacing="0" cellpadding="1"
						style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">
						<tr>
							<td style="width: 20%;">单位名称</td>
							<td colspan="4" style="width: 80%; word-break: break-all;text-align:left !important; "
								data-field="shippingCompany">
								{{ editableData.shippingCompany }}
							</td>
						</tr>
						<tr>
							<td>车号</td>
							<td>货物名称</td>
							<td>毛重</td>
							<td>皮重</td>
							<td>净重</td>
						</tr>
						<tr>
							<td data-field="autoLicense">{{ editableData.autoLicense }}</td>
							<td data-field="cargoName">
								<span>{{'石油焦' }}</span>
							</td>
							<td data-field="roughWeight">{{ editableData.roughWeight }}</td>
							<td data-field="tare">{{ editableData.tare }}</td>
							<td data-field="suttle">{{ editableData.suttle }}</td>
						</tr>
						<tr>
							<td data-field="autoLicense">{{' '}}</td>
							<td data-field="cargoName">{{' '}}</td>
							<td data-field="roughWeight">{{' '}}</td>
							<td data-field="tare">{{' '}}</td>
							<td data-field="suttle">{{' '}}</td>
						</tr>
						<tr>
							<td colspan="1">备注</td>
							<td colspan="2"></td>
							<td>司磅</td>
							<td data-field="weigher">{{ editableData.weigher }}</td>
						</tr>
					</table>
				</div>

				<!-- 模板7：河北鸿科碳素检斤单（新增） -->
				<div v-if="poundTemplateType === 7" class="pound-template template7">
					<div class="header-info">
						<div style="text-align: center; font-weight: bold; font-size: 18px;letter-spacing: 20px;">过磅单
						</div>
					</div>
					<div class="header-info"
						style="font-family: SimSun, serif; display: flex; justify-content: space-between;">
						<div class="print-time">{{ editableData.nowTime }}</div>
						<div>单位：吨</div>
					</div>
					<!-- 核心修复：所有行均为6列，无任何colspan错误 -->
					<table class="print-table" border="2" cellspacing="0" cellpadding="1"
						style="width: 100%; border-collapse: collapse; font-family: SimSun; table-layout: fixed;">
						<!-- 第一行：单位名称（2列，第二列占5列，总6列） -->
						<tr>
							<td style="width: 20%; text-align: center;">单位名称</td>
							<td colspan="5" style="width: 80%; word-break: break-all; text-align: left !important;"
								data-field="shippingCompany">
								<!-- caiOptions -->

								<el-select v-if="isPEditing" v-model="editableData.shippingCompany" filterable
									default-first-option :reserve-keyword="true" value-key="id"  placeholder="请输入或选择单位"
									style="width: 100%" clearable @change="handlePopupCaiConChange"
									:popper-options="{ 
									    modifiers: [
									      {
									        name: 'computeStyles',
									        options: {
									          adaptive: false  
									        }
									      }
									    ]
									  }"
									  popper-append-to-body="true"  
									
									>
									<el-option v-for="item in allOptions" :key="item.id" :label="item.companyName"
										:value="item.id">
										<!-- <span>{{ item.companyName }}</span> -->
									</el-option>
								</el-select>
								<span v-else>{{ editableData.shippingCompany || ' ' }}</span>


							</td>
						</tr>
						<!-- 第二行：表头（6列，每列≈13.33%，无空白） -->
						<tr>
							<td style="width: 10%; text-align: center;">车号</td> <!-- 缩减车号列宽 -->
							<td style="width: 20%; text-align: center;">货物名称</td> <!-- 增加货物名称列宽 -->
							<td style="width: 13.33%; text-align: center;">毛重</td>
							<td style="width: 13.33%; text-align: center;">皮重</td>
							<td style="width: 13.33%; text-align: center;">净重</td>
							<td style="width: 13.34%; text-align: center;">结算量</td>
						</tr>
						<!-- 第三行：数据行（6列，完全填满） -->
						<tr>
							<td data-field="autoLicense" style="text-align: center;">{{ editableData.autoLicense }}</td>
							<td data-field="cargoName" style="text-align: center;">
								<el-select v-if="isPEditing" v-model="editableData.deductingId" filterable
									default-first-option :reserve-keyword="false" placeholder="请输入或选择货名"
									style="width: 100%" clearable @change="handlePopupCargoChange">
									<el-option v-for="item in cargoOptions" :key="item.id" :label="item.cargoName"
										:value="item.id">
										<span>{{ item.cargoName }}</span>
									</el-option>
								</el-select>
								<span v-else>{{ editableData.cargoName || ' ' }}</span>
							</td>
							<td data-field="roughWeight" style="text-align: center;">{{ editableData.roughWeight }}</td>
							<td data-field="tare" style="text-align: center;">{{ editableData.tare }}</td>
							<td data-field="suttle" style="text-align: center;">{{ editableData.suttle }}</td>
							<td data-field="settlementSuttle" style="text-align: center;">
								{{ editableData.settlementSuttle || '-' }}
							</td>
						</tr>
						<!-- 第四行：空行（6列，无右侧空白） -->
						<tr>
							<td style="text-align: center;">{{' '}}</td>
							<td style="text-align: center;">{{' '}}</td>
							<td style="text-align: center;">{{' '}}</td>
							<td style="text-align: center;">{{' '}}</td>
							<td style="text-align: center;">{{' '}}</td>
							<td style="text-align: center;">{{' '}}</td>
						</tr>
						<!-- 第五行：备注+司磅（6列，适配布局） -->
						<tr>
							<td colspan="2" style="text-align: center;">备注</td>
							<td colspan="2" style="text-align: center;"></td>
							<td style="text-align: center;">司磅</td>
							<td data-field="weigher" style="text-align: center;">{{ editableData.weigher }}</td>
						</tr>
					</table>
				</div>
			</div>
		</div>
		<!-- 弹窗按钮 -->
		<template #footer>
			<div class="dialog-footer" style="text-align: right; margin-top: 10px;">
				<el-button type="success" @click="handleDPrint">打印</el-button>
				<el-button type="primary" @click="handleDPEdit" v-if="!isPEditing" style="margin-right: 8px;">
					编辑
				</el-button>
				<el-button type="success" @click="handleDPSave" v-if="isPEditing" style="margin-right: 8px;">
					保存
				</el-button>
				<el-button @click="handleDqx">取消</el-button>
			</div>
		</template>
	</el-dialog>


<el-dialog v-model="exportDialogVisible" title="导出" width="600px" :before-close="handleExportCancel">
	<el-form :model="exportForm" :rules="exportRules" ref="exportFormRef" label-width="120px" class="mt-4">
		<el-form-item label="过磅类型" prop="weighingType">
			<el-select v-model="exportForm.weighingType" placeholder="请选择过磅类型" clearable style="width: 100%">
				<el-option label="采购" value="1"></el-option>
				<el-option label="销售" value="2"></el-option>
			</el-select>
		</el-form-item>
		<el-form-item label="开始日期" prop="startDate">
			<el-date-picker v-model="exportForm.startDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
				placeholder="请选择开始日期" style="width: 100%"></el-date-picker>
		</el-form-item>
		<el-form-item label="结束日期" prop="endDate">
			<el-date-picker v-model="exportForm.endDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
				placeholder="请选择结束日期" style="width: 100%"></el-date-picker>
		</el-form-item>
		<el-form-item label="货物ID" prop="deductingId">
			<el-select v-model="exportForm.deductingId" placeholder="请选择货物" clearable filterable
				style="width: 100%">
				<el-option key="all-option" label="全部" value="__ALL__"></el-option>
				<el-option v-for="item in cargoOptions" :key="item.id" :label="item.cargoName"
					:value="item.id"></el-option>
			</el-select>
		</el-form-item>
		<!-- 新增发货单位ID -->
		<el-form-item label="发货单位" prop="shippingCompanyId">
			<el-select v-model="exportForm.shippingCompanyId" placeholder="请选择发货单位" clearable filterable
				style="width: 100%">
				<el-option key="all-shipping" label="全部" value="__ALL__"></el-option>
				<el-option v-for="item in caiOptions" :key="item.id" :label="item.companyName"
					:value="item.id"></el-option>
			</el-select>
		</el-form-item>
		<!-- 新增收货单位ID -->
		<el-form-item label="收货单位" prop="receivingCompanyId">
			<el-select v-model="exportForm.receivingCompanyId" placeholder="请选择收货单位" clearable filterable
				style="width: 100%">
				<el-option key="all-receiving" label="全部" value="__ALL__"></el-option>
				<el-option v-for="item in xiaoOptions" :key="item.id" :label="item.companyName"
					:value="item.id"></el-option>
			</el-select>
		</el-form-item>
	</el-form>
	<template #footer>
		<el-button @click="handleExportCancel">取消</el-button>
		<el-button type="primary" @click="handleExportSubmit">确认导出</el-button>
	</template>
</el-dialog>



</template>

<script setup lang="ts">
	import {
		ref,
		reactive,
		onMounted,
		nextTick,
		onBeforeUnmount,
		getCurrentInstance,
		computed
	} from 'vue';
	import {
		ElMessage,
		ElMessageBox,
		ElForm
	} from 'element-plus'
	import type { ComponentSize } from 'element-plus'
	import { ArrowLeft, Bottom } from '@element-plus/icons-vue'
	const size = ref<ComponentSize>('default')
	import cloneDeep from 'lodash/cloneDeep';
	import { useRouter } from 'vue-router'
	const router = useRouter()
	const {
		proxy
	} = getCurrentInstance()
	interface TableItem {
		updateTime : string
		autoLicense : string
		containerNum : string
		cargoName : string
		deductingId : string
		tare : number
		roughWeight : number
		suttle : number
		isEditing ?: boolean
		driverName : string
		specifications : string
		receivingCompany : string
		shippingCompany : string
		receivingCompanyId : string
		shippingCompanyId : string
		weigher : string
		weighingType : number
		originalData ?: Partial<TableItem>
		id : string
		countSuttle ?: number
		weightStatus : number
		isAdditionalRecording : number
		reviewer : string
		secondAweighingTime : string
		relyTare : number
		relyRoughWeight : number
		relySuttle : number
		settlementSuttle : number
		weightNumber : string
		remarks ?: string
	}


	// 模板选择下拉框的选项（对应现有7个模板，名称需清晰）
	const templateOptions = ref([
		{ label: "模板1：盛虹入库", value: 1 },
		{ label: "模板2：盛虹出库", value: 2 },
		{ label: "模板3：天津大港入库", value: 3 },
		{ label: "模板4：天津大港出库", value: 4 },
		{ label: "模板5：默认打印", value: 5 },
		{ label: "模板6：中石油燃料油", value: 6 },
		{ label: "模板7：元氏九天/砾乐风", value: 7 },
	]);
	// 4. 用户选中的模板类型（默认选中常用模板，比如模板5）
	const selectedTemplateType = ref(5);
	const isPEditing = ref(false)
	interface CompanyOption {
		companyName : string
		id : string
	}
	const cargoOptions = ref<{ cargoName : string, id : string }[]>([]);
	const caiOptions = ref<CompanyOption[]>([

	])
	const xiaoOptions = ref<CompanyOption[]>([

	])
	const allOptions = ref<CompanyOption[]>([

	])
	const options = [
		{
			value: 0,
			label: '未过磅',
		},
		{
			value: 1,
			label: '一次过磅完成',
		},
		{
			value: 2,
			label: '二次过磅完成',
		},

	]
	const viewDialogVisible = ref(false);
	const viewData = ref<TableItem | null>(null);
	const dialogVisible = ref(false)
	const poundTemplateType = ref(5);
	const isEditing = ref(false)
	const tableData = ref<TableItem[]>([

	])
	const role = localStorage.getItem('role');
	const editableFields = ['grossWeight', 'tareWeight', 'netWeight', 'driver', 'spec', 'weigher', 'carNo', 'goodsName', 'sender', 'receiver']
	let initialData = reactive({})
	let editableData = reactive({})

	const formInline = reactive({
		weighingDate: '',
		autoLicense: '',
		containerNum: '',
		weightStatus: null,
		cargoName: '',
		shippingCompanyId: '',
		receivingCompanyId: ''

	})

	const hslistQuery = reactive({
		current: 1,
		size: 5,

	})

	const exportDialogVisible = ref(false);
	const exportFormRef = ref<InstanceType<typeof ElForm> | null>(null);
	const exportForm = ref({
		weighingType: '',
		startDate: '',
		endDate: '',
		deductingId: '__ALL__',
		shippingCompanyId: '__ALL__', // 新增：发货单位ID，默认全部
		receivingCompanyId: '__ALL__'  // 新增：收货单位ID，默认全部
	});
	const exportRules = ref({
		weighingType: [
			{ required: true, message: '请选择过磅类型', trigger: 'change' }
		],
		startDate: [
			{ required: true, message: '请选择开始日期', trigger: 'change' }
		],
		endDate: [
			{ required: true, message: '请选择结束日期', trigger: 'change' }
		],
		deductingId: [
			{ required: false, message: '请选择货物（可选）', trigger: 'change' }
		],
		// 新增参数验证规则（可选，与货物ID保持一致）
			shippingCompanyId: [
				{ required: false, message: '请选择发货单位（可选）', trigger: 'change' }
			],
			receivingCompanyId: [
				{ required: false, message: '请选择收货单位（可选）', trigger: 'change' }
			]
	});

	const handleExportOpen = () => {
		if (exportFormRef.value) {
			exportFormRef.value.resetFields();
			exportForm.value.deductingId = '__ALL__';
			exportForm.value.shippingCompanyId = '__ALL__';
			exportForm.value.receivingCompanyId = '__ALL__';
		}
		exportDialogVisible.value = true;
	};

	const handleExportCancel = () => {
		exportDialogVisible.value = false;
		if (exportFormRef.value) {
				exportFormRef.value.resetFields();
			}
	};

	const handleExportSubmit = async () => {
		if (!exportFormRef.value) return;
		const isValid = await exportFormRef.value.validate();
		if (!isValid) return;
	
		try {
			const baseUrl = 'weighingSheet/exportData';
			const baseApi = import.meta.env.VITE_API || '';
			const params = new URLSearchParams();
	
			// 原有参数
			params.append('weighingType', exportForm.value.weighingType);
			params.append('startDate', exportForm.value.startDate);
			params.append('endDate', exportForm.value.endDate);
			const finalDeductingId = exportForm.value.deductingId === '__ALL__' ? '' : exportForm.value.deductingId;
			params.append('deductingId', finalDeductingId);
	
			// 新增参数处理 - 发货单位ID
			const finalShippingId = exportForm.value.shippingCompanyId === '__ALL__' ? '' : exportForm.value.shippingCompanyId;
			params.append('shippingCompanyId', finalShippingId);
	
			// 新增参数处理 - 收货单位ID
			const finalReceivingId = exportForm.value.receivingCompanyId === '__ALL__' ? '' : exportForm.value.receivingCompanyId;
			params.append('receivingCompanyId', finalReceivingId);
	
			const downloadUrl = `${baseApi}${baseUrl}?${params.toString()}`;
			window.location.href = downloadUrl;
	
			ElMessage.success('正在准备下载文件，请稍候...');
			exportDialogVisible.value = false;
	
		} catch (error: any) {
			console.error('导出参数处理错误:', error);
			ElMessage.error('参数错误，导出失败');
		}
	};

	const getCargoNameList = async () => {
		try {
			const res = await proxy.$request.getCargoNameList()
			cargoOptions.value = []
			if (res?.data?.code === 200 && res.data.result) {
				cargoOptions.value = res.data.result
			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			cargoOptions.value = []
			ElMessage.error(error.data.message || '网络请求异常')
		}
	}

	const handleDPEdit = () => {
		isPEditing.value = true
	}
	const handleDPSave = () => {
		isPEditing.value = false
	}
	const handleDqx = () => {
		dialogVisible.value = false
		isPEditing.value = false
	}
	const handleBack = () => {
		router.go(-1)
	}
	const getStatusText = (status) => {
		const map = {
			0: '未过磅',
			1: '一次过磅完成',
			2: '二次过磅完成'
		}
		return map[status] || '未知'
	}
	const calculateSuttle = (row) => {
		const formattedRoughWeight = row.roughWeight ? Number(row.roughWeight) : 0;
		const formattedTare = row.tare ? Number(row.tare) : 0;

		row.roughWeight = Number(formattedRoughWeight.toFixed(2));
		row.tare = Number(formattedTare.toFixed(2));

		if (formattedRoughWeight >= 0 && formattedTare >= 0) {
			const suttle = Number((formattedRoughWeight - formattedTare).toFixed(2));
			row.suttle = suttle;
			row.settlementSuttle = Number((suttle * (row.countSuttle || 1)).toFixed(2));
		} else {
			row.suttle = 0;
			row.settlementSuttle = 0;
		}
	};
	const handleCargoChange = (row, deductingId) => {
		const selectedCargo = cargoOptions.value.find(item => item.id === deductingId);
		if (selectedCargo) {
			row.cargoName = selectedCargo.cargoName;
		} else {
			row.cargoName = '';
		}
	}
	const handleCancelEdit = (row : TableItem) => {
		if (row.originalData) {
			Object.assign(row, row.originalData);
			delete row.originalData;
		}
		row.isEditing = false;
	};
	const handleRollback = async (row : TableItem) => {
		const confirmText = row.weightStatus === 1
			? "是否确认回退至【未过磅】状态？"
			: "是否确认回退至【一次过磅】状态？";

		try {
			await ElMessageBox.confirm(
				confirmText,
				"回退确认",
				{
					confirmButtonText: "确认回退",
					cancelButtonText: "取消",
					type: "warning"
				}
			);

			const res = await proxy.$request.rollbackWeighing({
				id: row.id
			});

			if (res?.data?.code === 200) {
				ElMessage.success("回退成功！");
				const params = Object.assign({}, formInline, hslistQuery);
				fetchData(params);
			} else {
				ElMessage.error(res?.data?.message || "回退失败，请重试");
			}
		} catch (error : any) {
			if (error.name === "MessageBoxCancel") {
				return;
			}
			console.error("回退接口调用失败：", error);
			ElMessage.error(error.data?.message || "取消回退!");
		}
	};
	const formatDateToYMD = (date : string | Date | undefined) : string => {
		if (!date) return '';

		const targetDate = typeof date === 'string' ? new Date(date) : date;

		if (isNaN(targetDate.getTime())) return '';

		const year = targetDate.getFullYear();
		const month = String(targetDate.getMonth() + 1).padStart(2, '0');
		const day = String(targetDate.getDate()).padStart(2, '0');

		return `${year}年${month}月${day}日`;
	}
	const fetchData = async (params) => {
		try {
			const res = await proxy.$request.getHisList(params)

			if (res?.data?.code === 200) {
				tableData.value = res.data.result?.resultData || []
				hstotal.value = res.data.result?.totalRows || 0
			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			ElMessage.error(error.data.message || '网络请求异常')
		}
	}
	const handlePopupCargoChange = (selectedId : string) => {
		const selectedCargo = cargoOptions.value.find(item => item.id === selectedId);
		editableData.cargoName = selectedCargo ? selectedCargo.cargoName : '';
	}



	const handlePopupCaiConChange = (selectedId : string) => {
		const neWid = allOptions.value.find(item => item.id === selectedId);
		editableData.shippingCompany = neWid ? neWid.companyName : '';
	}
	const handleCompanyChange = async (row : TableItem, type : 'shipping' | 'receiving') => {
		const companyId = type === 'shipping' ? row.shippingCompanyId : row.receivingCompanyId;
		if (!companyId) return;

		try {
			const res = await proxy.$request.getCompanySelect({ id: companyId });
			if (res.data.code === 200) {
				row.countSuttle = res.data.result?.[0]?.suttle || 1;
				calculateSuttle(row);
			} else {
				row.countSuttle = 1;
				ElMessage.error(res.data.message || '获取厂家结算系数失败');
			}
		} catch (error : any) {
			row.countSuttle = 1;
			console.error('获取厂家结算系数异常:', error);
			ElMessage.error(error.data?.message || '网络请求异常');
		}
	};

	const handleView = (row : TableItem) => {
		viewData.value = { ...row };
		viewDialogVisible.value = true;
	}
	const handleSizeChange = (val : number) => {
		hslistQuery.size = val;
		hslistQuery.current = 1;
		const params = Object.assign({}, formInline, hslistQuery);
		fetchData(params);
	}
	const handleCurrentChange = (val : number) => {
		hslistQuery.current = val;
		const params = Object.assign({}, formInline, hslistQuery)
		fetchData(params)
	}

	const onSubmit = () => {
		const params = Object.assign({}, formInline, hslistQuery)
		fetchData(params)
	}

	const handleInput = (e : Event) => {
		const cell = e.target as HTMLTableCellElement
		const field = cell.getAttribute('data-field')
		if (!field) return

		(editableData as any)[field] = cell.textContent?.trim() || ''

		if (field === 'grossWeight') {
			calculateWeights('gross')
		} else if (field === 'tareWeight') {
			calculateWeights('tare')
		} else if (field === 'netWeight') {
			calculateWeights('net')
		}
	}
	const calculateWeights = (field : 'gross' | 'tare' | 'net') => {
		const gross = parseFloat(editableData.grossWeight) || 0
		const tare = parseFloat(editableData.tareWeight) || 0
		const net = parseFloat(editableData.netWeight) || 0

		if (field === 'gross') {
			editableData.netWeight = (gross - tare).toString()
		} else if (field === 'tare') {
			editableData.netWeight = (gross - tare).toString()
		} else if (field === 'net') {
			if (gross > 0) {
				editableData.tareWeight = (gross - net).toString()
			} else if (tare > 0) {
				editableData.grossWeight = (net + tare).toString()
			}
		}
	}
	const handleDEdit = () => {
		isEditing.value = true
		nextTick(() => {
			const cells = document.querySelectorAll('.print-table td[data-field]') as NodeListOf<HTMLTableCellElement>
			cells.forEach(cell => {
				const field = cell.getAttribute('data-field') as string

				if (editableFields.includes(field)) {
					cell.setAttribute('contenteditable', 'true')
					cell.style.backgroundColor = '#f5f7fa'
					cell.addEventListener('input', handleInput)
				} else {
					cell.setAttribute('contenteditable', 'false')
					cell.style.backgroundColor = 'transparent'
				}
			})
		})
	}

	const handleDSave = () => {
		const validateAndConvertWeight = (value : string) => {
			const num = parseFloat(value)
			return isNaN(num) ? '0' : num.toString()
		}

		editableData.grossWeight = validateAndConvertWeight(editableData.grossWeight)
		editableData.tareWeight = validateAndConvertWeight(editableData.tareWeight)
		editableData.netWeight = validateAndConvertWeight(editableData.netWeight)

		calculateWeights('gross')

		isEditing.value = false

		console.log('保存成功，数据为：', { ...editableData })

		ElMessage.success('数据保存成功')
	}
	const handleDPrint = () => {
		isPEditing.value = false;
		setTimeout(() => {
			const printContainer = document.createElement('div');
			let templateContent = null;
			let customPrintStyle = '';

			switch (poundTemplateType.value) {
				case 1: templateContent = document.querySelector('.pound-template.template1')?.cloneNode(true); break;
				case 2: templateContent = document.querySelector('.pound-template.template2')?.cloneNode(true); break;
				case 3: templateContent = document.querySelector('.pound-template.template3')?.cloneNode(true); break;
				case 4: templateContent = document.querySelector('.pound-template.template4')?.cloneNode(true); break;
				case 5: templateContent = document.querySelector('.pound-template.template5')?.cloneNode(true); break;
				case 6: templateContent = document.querySelector('.pound-template.template6')?.cloneNode(true); break;
				case 7:
					templateContent = document.querySelector('.pound-template.template7')?.cloneNode(true);
					if (templateContent) {

						const tableParent = templateContent.querySelector('.dybox');
						if (tableParent) {
							tableParent.style.width = '100% !important';
							tableParent.style.maxWidth = '100% !important';
							tableParent.style.overflow = 'visible !important';
						}

						// 2. 表格锁定布局，列宽按设定生效
						const printTable = templateContent.querySelector('.print-table');
						if (printTable) {
							printTable.style.tableLayout = 'fixed !important';
							printTable.style.width = '100% !important';
							printTable.style.maxWidth = '100% !important';
							printTable.style.borderCollapse = 'collapse !important';
						}

						// 3. 列宽核心调整：恢复车号+仅压重量列+增大货物名称
						const rows = templateContent.querySelectorAll('.print-table tr');
						rows.forEach((row, rowIndex) => {
							const cells = row.querySelectorAll('td');
							cells.forEach(cell => {
								cell.style.border = '2px solid #000 !important';
								cell.style.padding = '0 3px !important'; // 最小内边距，省空间
								cell.style.verticalAlign = 'middle !important';
								cell.style.textAlign = 'center !important';
								cell.style.fontSize = '18px !important';
								cell.style.fontWeight = '600 !important';
								// 货物名称列：不换行（核心）
								if (Array.from(row.cells).indexOf(cell) === 1) {
									cell.style.whiteSpace = 'nowrap !important';
									cell.style.overflow = 'visible !important';
								} else {
									cell.style.whiteSpace = 'nowrap !important';
								}
							});

							// 新列宽比例（总和100%）：
							// 车号恢复8%（不减小），重量列压至3%，货物名称增至72%
							if (cells.length >= 6) {
								cells[0].style.width = '10% !important';    // 车号：恢复8%（不减小，之前的宽度）
								cells[0].style.maxWidth = '10% !important';
								cells[1].style.width = '78% !important';   // 货物名称：增至72%（核心增大）
								cells[1].style.maxWidth = '78% !important';
								cells[2].style.width = '3% !important';    // 毛重：压至3%（仅够显示“99.99”）
								cells[2].style.maxWidth = '3% !important';
								cells[3].style.width = '3% !important';    // 皮重：压至3%（同毛重）
								cells[3].style.maxWidth = '3% !important';
								cells[4].style.width = '3% !important';    // 净重：压至3%（同毛重）
								cells[4].style.maxWidth = '3% !important';
								cells[5].style.width = '11% !important';   // 结算量：11%（补全100%）
								cells[5].style.maxWidth = '11% !important';
							}

							// 空行处理（不变）
							if (rowIndex === 3 && cells.length === 6) {
								row.style.height = '45px !important';
								row.style.minHeight = '45px !important';
								cells.forEach(cell => {
									cell.innerHTML = '&nbsp;';
									cell.style.minHeight = '45px !important';
								});
							} else {
								row.style.height = '45px !important';
								row.style.minHeight = '45px !important';
							}
						});

						// 标题样式（不变）
						const headerInfos = templateContent.querySelectorAll('.header-info');
						headerInfos.forEach((header, index) => {
							if (index === 0) {
								header.querySelectorAll('div').forEach(title => {
									title.style.fontSize = '20px !important';
									title.style.marginBottom = '8px !important';
								});
							}
							if (index === 1) {
								header.style.marginBottom = '0.1cm !important';
								header.querySelectorAll('div').forEach(info => {
									info.style.fontSize = '15px !important';
								});
							}
						});
					}

					// 4. CSS同步修正：恢复车号宽度，仅压重量列
					customPrintStyle = `
          .pound-template.template7 .dybox {
            width: 100% !important;
            max-width: 100% !important;
            overflow: visible !important;
            padding: 0 !important;
          }
          .pound-template.template7 .print-table {
            table-layout: fixed !important;
            width: 100% !important;
            max-width: 100% !important;
            border-collapse: collapse !important;
            margin: 0 !important;
          }
          /* 列宽修正：车号8%，重量列3%，货物名称72% */
          .pound-template.template7 .print-table tr td:nth-child(1) {
            width: 10% !important;
            max-width: 10% !important;
          }
          .pound-template.template7 .print-table tr td:nth-child(2) {
            width: 78% !important;
            max-width: 78% !important;
            white-space: nowrap !important;
            overflow: visible !important;
          }
          .pound-template.template7 .print-table tr td:nth-child(3) {
            width: 3% !important;
            max-width: 3% !important;
          }
          .pound-template.template7 .print-table tr td:nth-child(4) {
            width: 3% !important;
            max-width: 3% !important;
          }
          .pound-template.template7 .print-table tr td:nth-child(5) {
            width: 3% !important;
            max-width: 3% !important;
          }
          .pound-template.template7 .print-table tr td:nth-child(6) {
            width: 11% !important;
            max-width: 11% !important;
          }
          .pound-template.template7 .print-table td {
            font-size: 18px !important;
            padding: 0 3px !important;
            vertical-align: middle !important;
          }
          .pound-template.template7 .print-table tr {
            height: 45px !important;
            min-height: 45px !important;
          }
        `;
					break;
				default: templateContent = document.querySelector('.pound-template.template6')?.cloneNode(true);
			}

			// 原通用样式处理（不变：时间/吨位置和模板6一致）
			if (templateContent) {
				const titleElements = templateContent.querySelectorAll('.header-info > div');
				titleElements.forEach((titleEl, index) => {
					let targetFontSize = '';
					if (titleEl.parentElement.classList.contains('header-info') && index === 0) {
						targetFontSize = poundTemplateType.value === 5 ? '0.7cm' : '0.8cm';
					} else if (titleEl.parentElement.classList.contains('header-info') && index === 1) {
						targetFontSize = poundTemplateType.value === 5 ? '0.6cm' : '0.7cm';
					} else if (titleEl.parentElement.classList.contains('header-info') && (titleEl.textContent.includes('单位：') || titleEl.textContent.includes('No.'))) {
						targetFontSize = poundTemplateType.value === 5 ? '0.6cm' : '0.5cm';
					}
					if (targetFontSize) {
						titleEl.style.setProperty('font-size', targetFontSize, 'important');
						titleEl.style.setProperty('font-weight', '700', 'important');
					}
				});

				// “吨”位置（不变）
				const unitTonElement = Array.from(templateContent.querySelectorAll('.header-info:nth-child(2) > div')).find(el => el.textContent?.trim() === '单位：吨');
				if (unitTonElement) {
					unitTonElement.style.setProperty('padding-right', '3cm', 'important');
				}

				// 时间位置（不变）
				const timeElement = templateContent.querySelector('.print-time');
				if (timeElement) {
					const fontSize = poundTemplateType.value === 5 ? '0.5cm' : '0.5cm';
					timeElement.style.setProperty('font-size', fontSize, 'important');
					timeElement.style.marginLeft = poundTemplateType.value === 5 ? '0.8cm' : '5cm';
					timeElement.style.setProperty('font-weight', '700', 'important');
				}

				printContainer.appendChild(templateContent);
			} else {
				ElMessage.error('未找到打印模板，请重试');
				return;
			}

			const infoContainer = templateContent.querySelector('.header-info:nth-child(2)');
			if (infoContainer) {
				const marginBottom = poundTemplateType.value === 5 ? '0cm' : '0cm';
				infoContainer.style.setProperty('margin-bottom', marginBottom, 'important');
				infoContainer.style.setProperty('margin-top', '0.4cm !important');
				infoContainer.style.setProperty('padding', '0 !important');
			}

			// 生成最终打印样式（不变）
			const style = document.createElement('style');
			let printStyle = '';
			if (poundTemplateType.value === 5) {
				printStyle = `@page { size: A4 portrait !important; margin: 0.5cm !important; } body { width: 21cm !important; height: auto !important; margin: 0; padding: 0; font-family: SimSun, serif !important; } .pound-template.template5 { width: 100% !important; height: auto !important; } .template5 .print-table { width: 100% !important; border-collapse: collapse !important; font-size: 0.9cm !important; line-height: 1.2cm !important; } .template5 .print-table tr { height: 1.2cm !important; min-height: 1.2cm !important; line-height: 1.2cm !important; font-weight: 600 !important; } .template5 .print-table td { border: 2px solid #000 !important; padding: 0 0.2cm !important; vertical-align: middle !important; text-align: center !important; white-space: nowrap !important; font-weight: 600 !important; } .template5 .header-info:nth-child(2) { margin-bottom: 0.05cm !important; margin-top: 0 !important; padding: 0 !important; display: flex !important; justify-content: space-between !important; } .template5 .header-info:first-child div:first-child { font-size: 1.1cm !important; margin-bottom: 0.3cm !important; } .template5 .header-info:first-child div:last-child { font-size: 0.7cm !important; } .template5 .header-info:nth-child(2) > div { font-size: 0.7cm !important; font-weight: 600 !important; } .dybox-container { transform: none !important; width: 100% !important; height: auto !important; overflow: visible !important; } .dybox { width: 100% !important; height: auto !important; padding: 10px !important; border: none !important; }`;
			} else {
				printStyle = `
        @page { size: A4 portrait !important; margin: 0.5cm !important; }
        body { width: 21cm !important; height: auto !important; margin: 0; padding: 0; font-family: SimSun, serif !important; }
        .dybox-container {
          transform: none !important;
          width: 100% !important;
          max-width: 100% !important;
          overflow: visible !important;
        }
        .dybox {
          width: 100% !important;
          max-width: 100% !important;
          padding: 10px !important;
          border: none !important;
        }
        .pound-template { width: 100% !important; height: auto !important; }
        .print-table { width: 100% !important; border-collapse: collapse !important; font-size: 16px !important; }
        .print-table tr { height: 45px !important; min-height: 45px !important; line-height: 45px !important; }
        .print-table td { border: 2px solid #000 !important; padding: 0 10px !important; vertical-align: middle !important; text-align: center !important; white-space: nowrap !important; font-size: 18px !important; font-weight: 600 !important; }
        .pound-template .header-info:nth-child(2) { margin-bottom: 0.1cm !important; margin-top: 0.2cm !important; padding: 0 !important; display: flex !important; justify-content: space-between !important; }
        .header-info:first-child div:first-child { font-size: 20px !important; font-weight: bold !important; margin-bottom: 8px !important; }
        .header-info:first-child div:last-child { font-size: 20px !important; font-weight: 700 !important; }
        .header-info:nth-child(2) > div { font-size: 15px !important; font-weight: 600 !important; }
        ${poundTemplateType.value === 7 ? customPrintStyle : ''}
      `;
			}
			style.innerHTML = printStyle;
			printContainer.appendChild(style);

			// 打开打印窗口（足够宽，确保表格展开）
			const printWindow = window.open('', '_blank');
			if (printWindow) {
				printWindow.document.title = "过磅单打印";
				printWindow.resizeTo(1200, 1130);
				printWindow.document.write(`<!DOCTYPE html><html><head><title>过磅单打印</title></head><body>${printContainer.outerHTML}</body></html>`);
				printWindow.document.close();
				printWindow.onload = () => {
					printWindow.focus();
					setTimeout(() => {
						printWindow.print();
						printWindow.close();
					}, 800);
				};
			} else {
				ElMessage.error('浏览器阻止了弹出窗口，请允许弹出后重试');
			}
		}, 300)
	};
	const handleReset = () => {
		formInline.weighingDate = '';
		formInline.autoLicense = '';
		formInline.containerNum = '';
		formInline.cargoName = '';
		formInline.shippingCompanyId = '';
		formInline.receivingCompanyId = '';
		formInline.weightStatus = null;

		hslistQuery.current = 1;
		const params = Object.assign({}, formInline, hslistQuery);
		fetchData(params);
	};
	const handleTemplateChange = () => {
		// 选择的模板类型同步到渲染用的poundTemplateType
		poundTemplateType.value = selectedTemplateType.value;
		// 重置当前模板的编辑状态（避免切换后残留编辑态）
		isPEditing.value = false;
		// 重新初始化当前行数据（确保不同模板渲染正确数据）
		if (currentPrintRow.value) {
			Object.assign(editableData, initialData);
		}
		ElMessage.info(`已切换至${templateOptions.value.find(item => item.value === selectedTemplateType.value)?.label}`);
	};


	const getFormattedTime = () => {
		const now = new Date()
		const year = now.getFullYear()
		const month = String(now.getMonth() + 1).padStart(2, '0')
		const day = String(now.getDate()).padStart(2, '0')
		const hours = String(now.getHours()).padStart(2, '0')
		const minutes = String(now.getMinutes()).padStart(2, '0')
		const seconds = String(now.getSeconds()).padStart(2, '0')

		return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
	}
	const YMD_FORMAT_TEMPLATES = [1, 2, 3, 4, 5, 6, 7]; // 新增模板7
	const handlePrint = (row) => {
		proxy.$request.getPrintId({
			deductingId: row.weighingType === 1 ? row.receivingCompanyId : row.shippingCompanyId,
			weighingType: row.weighingType
		}).then((res) => {
			if (res.data.code === 200) {
				poundTemplateType.value = res.data.result ? Number(res.data.result.modelKey) : 5; // 默认模板5
				selectedTemplateType.value = res.data.result ? Number(res.data.result.modelKey) : 5; // 默认模板5
				initialData = cloneDeep(row);
				initialData.deductingId = row.deductingId || '';
				// 模板7特殊字段处理
				initialData.weighingDate = row.updateTime ? formatDateToYMD(row.updateTime) : '';
				initialData.remarks = row.remarks || '';

				// 通用字段处理
				initialData.nowTime = YMD_FORMAT_TEMPLATES.includes(poundTemplateType.value)
					? formatDateToYMD(new Date())
					: getFormattedTime();
				initialData.shippingCompany = initialData.shippingCompany || "未知发货单位";
				initialData.receivingCompany = initialData.receivingCompany || "未知收货单位";
				initialData.autoLicense = initialData.autoLicense || "未知车牌";
				initialData.containerNum = initialData.containerNum || "无";
				initialData.cargoName = initialData.cargoName || "石油焦";
				initialData.roughWeight = initialData.roughWeight || 45.48;
				initialData.tare = initialData.tare || 17.58;
				initialData.suttle = initialData.suttle || 27.90;
				initialData.settlementSuttle = initialData.settlementSuttle || 0;
				initialData.weigher = initialData.weigher || "未知司磅员";
				initialData.weightNumber = initialData.weightNumber || `HK${Date.now()}`;

				Object.assign(editableData, initialData);
				dialogVisible.value = true;
			} else {
				ElMessage.error(res.data.message);
			}
		}).catch((err) => {
			console.log('err', err);
			poundTemplateType.value = 7; // 异常时使用模板7
			initialData = cloneDeep(row);
			initialData.deductingId = row.deductingId || '';
			initialData.weighingDate = row.updateTime ? formatDateToYMD(row.updateTime) : '';
			initialData.remarks = row.remarks || '';
			initialData.nowTime = YMD_FORMAT_TEMPLATES.includes(poundTemplateType.value)
				? formatDateToYMD(new Date())
				: getFormattedTime();
			initialData.shippingCompany = initialData.shippingCompany || "未知发货单位";
			initialData.receivingCompany = initialData.receivingCompany || "未知收货单位";
			initialData.autoLicense = initialData.autoLicense || "未知车牌";
			initialData.containerNum = initialData.containerNum || "无";
			initialData.cargoName = initialData.cargoName || "石油焦";
			initialData.roughWeight = initialData.roughWeight || 45.48;
			initialData.tare = initialData.tare || 17.58;
			initialData.suttle = initialData.suttle || 27.90;
			initialData.weigher = initialData.weigher || "未知司磅员";
			initialData.weightNumber = initialData.weightNumber || `HK${Date.now()}`;

			Object.assign(editableData, initialData);
			dialogVisible.value = true;
			ElMessage.error(err.data?.message || '打印数据获取失败');
		});
	};

	const handleClose = () => {
		Object.assign(editableData, initialData)
		isEditing.value = false
		dialogVisible.value = false
	}

	const hstotal = ref(5)

	const handleEdit = (row : TableItem) => {
		row.originalData = { ...row };
		row.isEditing = true;

		row.roughWeight = row.roughWeight ? Number(Number(row.roughWeight).toFixed(2)) : 0;
		row.tare = row.tare ? Number(Number(row.tare).toFixed(2)) : 0;
		row.suttle = row.suttle ? Number(Number(row.suttle).toFixed(2)) : 0;
		row.settlementSuttle = row.settlementSuttle ? Number(Number(row.settlementSuttle).toFixed(2)) : 0;

		proxy.$request.getCompanySelect({ id: row.weighingType === 1 ? row.shippingCompanyId : row.receivingCompanyId })
			.then((res) => {
				if (res.data.code === 200) {
					if (row.weightStatus === 1) {
						return
					} else {
						row.countSuttle = res.data.result?.[0]?.suttle || 1;
						calculateSuttle(row);
					}
				} else {
					row.countSuttle = 1;
					ElMessage.error(res.data.message);
				}
			})
			.catch((err) => {
				console.log('err', err);
				row.countSuttle = 1;
				ElMessage.error(err.data?.messgae || '获取厂家系数异常');
			});
	};

	const setHis = async (row) => {
		try {
			const formattedData = {
				autoLicense: row.autoLicense,
				containerNum: row.containerNum,
				cargoName: row.cargoName,
				shippingCompanyId: row.shippingCompanyId,
				id: row.id,
				weigher: row.weigher,
				deductingId: row.deductingId,
				roughWeight: Number(Number(row.roughWeight).toFixed(2)),
				tare: Number(Number(row.tare).toFixed(2)),
				suttle: Number(Number(row.suttle).toFixed(2)),
				receivingCompanyId: row.receivingCompanyId,
				driverName: row.driverName,
				specifications: row.specifications,
				settlementSuttle: Number(Number(row.settlementSuttle).toFixed(2))
			};
			const res = await proxy.$request.setHis(formattedData);
			if (res?.data?.code === 200) {
				row.isEditing = false;
				const params = Object.assign({}, formInline, hslistQuery);
				fetchData(params);
				ElMessage.success('修改成功');
			} else {
				ElMessage.error(res?.data?.message || '请求失败');
			}
		} catch (error : any) {
			console.error('API请求错误:', error);
			ElMessage.error(error.data?.message || '网络请求异常');
		}
	};

	const handleSave = (row : TableItem) => {
		setHis(row)
	}
	const getCompanyNameList = async (num) => {
	  try {
	    const res = await proxy.$request.getCompanySelect({ companyType: num });
	    if (res?.data?.code === 200) {
	      if (res.data.result) {
	        // 1. 先处理原始数据：统一 id 为字符串类型 + 过滤无效数据
	        const companyList = (res.data.result || [])
	          .map(item => ({
	            ...item, // 保留原有所有字段
	            // 核心：将 id 转为字符串（统一类型），空值转为空字符串（避免 null/undefined）
	            id: item.id != null ? String(item.id) : ''
	          }))
	          .filter(item => item.id); // 过滤掉 id 为空字符串的无效数据（可选但推荐）
	
	        // 2. 原有逻辑：给对应选项赋值（此时 caiOptions/xiaoOptions 的 id 已统一为字符串）
	        if (num === 1) {
	          caiOptions.value = [];
	          caiOptions.value = companyList;
	        }
	        if (num === 2) {
	          xiaoOptions.value = [];
	          xiaoOptions.value = companyList;
	        }
	
	     
	        allOptions.value.push(...companyList);
	        const uniqueList = Array.from(
	          // 基于统一后的字符串 id 去重，彻底避免重复 key
	          new Map(allOptions.value.map(item => [item.id, item])).values()
	        );
	        allOptions.value = uniqueList;
	
	      
	      }
	    } else {
	      ElMessage.error(res?.data?.message || '请求失败');
	    }
	  } catch (error: any) {
	    console.error('API请求错误:', error);
	    // 修复：避免 error 无 data 属性时报错（添加可选链）
	    ElMessage.error(error?.data?.message || '网络请求异常');
	  }
	};
	onMounted(async () => {
		const params = Object.assign({}, formInline, hslistQuery)
		fetchData(params)
		await Promise.all([
			getCompanyNameList(1),
			getCompanyNameList(2),
			getCargoNameList()
		])
		
		 
	})

	onBeforeUnmount(() => {
		const cells = document.querySelectorAll('.print-table td[data-field]')
		cells.forEach(cell => cell.removeEventListener('input', handleInput))
	})
</script>
<style lang="scss">
	.print-dialog {
		width: 100% !important;
		max-width: 1050px !important;
		padding: 15px !important;

		.el-dialog__body {
			padding: 15px !important;
			overflow: auto !important;
			max-height: 80vh !important;
		}
	}

	.template1 .print-table tr,
	.template2 .print-table tr,
	.template3 .print-table tr,
	.template4 .print-table tr,
	.template5 .print-table tr,
	.template6 .print-table tr,
	.template7 .print-table tr {
		height: 40px !important;
		min-height: 40px !important;
		line-height: 40px !important;
	}

	.template1 .print-table td,
	.template2 .print-table td,
	.template3 .print-table td,
	.template4 .print-table td,
	.template6 .print-table td {
		padding: 0 8px !important;
		vertical-align: middle !important;
		white-space: nowrap !important;
		overflow: hidden !important;
		text-overflow: ellipsis !important;
		text-align: center !important;
	}

	.dybox-container {
		width: 100% !important;
		transform: none !important;
	}

	.dybox {
		width: 100% !important;
		padding: 15px !important;
		border: 2px dashed #ccc !important;
		box-sizing: border-box !important;

	}

	.header-info {
		margin: 0px 0px !important;
		line-height: 1.2 !important;
		text-align: center !important;
		font-size: 18px !important;
	}

	.header-info:first-child div:first-child {
		font-size: 20px !important;
		margin-bottom: 5px !important;
	}

	.print-table {
		width: 100% !important;
		font-size: 20px !important;
		font-weight: 600;
		border-collapse: collapse !important;
		margin: 0px 0px 10px 0px !important;
	}

	.print-table td {
		border: 2px solid #000 !important;
		padding: 5px 8px !important;
		text-align: center !important;
		vertical-align: middle !important;
	}

	.template5 .print-table {
		font-size: 20px !important;
		max-width: 100% !important;
		table-layout: auto !important;
		border-collapse: collapse !important;
		margin: 10px 0 !important;
	}

	.template5 .print-table tr {
		height: 40px !important;
		min-height: 40px !important;
		line-height: 40px !important;
	}

	.template5 .print-table td {
		padding: 0 8px !important;
		border: 2px solid #000 !important;
		vertical-align: middle !important;
		white-space: nowrap !important;
		overflow: hidden !important;
		text-overflow: ellipsis !important;
		text-align: center !important;
	}

	.template5 .header-info {
		&>div:first-child {
			font-size: 24px !important;
			margin-bottom: 10px !important;
		}

		&>div:last-child {
			font-size: 18px !important;
			margin-bottom: 8px !important;
		}
	}

	.template5 .header-info:nth-child(2)>div {
		font-size: 16px !important;
		font-weight: 600 !important;
	}

	.template7 .print-table {
		width: 100% !important;
		font-size: 20px !important;
		font-weight: 600;
		border-collapse: collapse !important;
		margin: 10px 0 !important;
		table-layout: fixed !important; // 锁定布局，确保列宽生效
	}

	// 列宽分配：货物名称列占35%，重量列各占10%
	.template7 .print-table tr td:nth-child(1) {
		width: 8% !important;
	}

	// 车号（压缩）
	.template7 .print-table tr td:nth-child(2) {
		width: 35% !important;
	}

	// 货物名称（增大）
	.template7 .print-table tr td:nth-child(3) {
		width: 10% !important;
	}

	// 毛重（减小）
	.template7 .print-table tr td:nth-child(4) {
		width: 10% !important;
	}

	// 皮重（减小）
	.template7 .print-table tr td:nth-child(5) {
		width: 10% !important;
	}

	// 净重（减小）
	.template7 .print-table tr td:nth-child(6) {
		width: 17% !important;
	}

	// 结算量（适配剩余宽度）

	.template7 .print-table td {
		border: 2px solid #000 !important;
		padding: 5px 5px !important; // 减少内边距，不挤压列宽
		text-align: center !important;
		vertical-align: middle !important;
		white-space: normal !important; // 允许文字换行
		word-break: break-all !important; // 长货名强制拆分
		line-height: 1.3 !important; // 换行后保持行高，避免重叠
	}

	.template7 .header-info {
		margin: 5px 0 !important;
		line-height: 1.5 !important;
		font-size: 16px !important;
	}

	.template7 .header-info:first-child div:first-child {
		font-size: 20px !important;
		margin-bottom: 5px !important;
	}

	@media print {
		@page {
			size: A4 portrait !important;
			margin: 0.5cm !important;
		}

		body {
			font-family: SimSun, serif !important;
			-webkit-print-color-adjust: exact !important;
			width: 21cm !important;
			height: auto !important;
			margin: 0 !important;
			padding: 0 !important;
			overflow: visible !important;
		}

		.header-info:nth-child(2) .print-time {
			font-size: 1.4cm !important;
			font-weight: 700 !important;
			margin-left: 0.5cm !important;
			line-height: 1.2cm !important;
			vertical-align: middle !important;
			margin-top: 0.4cm !important;
		}

		.template5 .header-info:nth-child(2) .print-time {
			font-size: 1.2cm !important;
			margin-left: 0.1cm !important;
		}

		.header-info>div:first-child {
			font-size: 1.2cm !important;
			text-align: right !important;
			padding-right: 1cm;
		}

		.template5 .header-info>div:first-child {
			font-size: 1.4cm !important;
			padding-right: 1.5cm;
		}

		.template5 {
			@page {
				size: A4 portrait !important;
				margin: 0.5cm !important;
			}

			body {
				width: 21cm !important;
				height: auto !important;
				margin: 0 !important;
				padding: 0 !important;
			}

			.print-table {
				font-size: 0.8cm !important;
				font-weight: 600 !important;
				width: 100% !important;
				border-collapse: collapse !important;
				table-layout: auto !important;
			}

			.print-table tr {
				height: 1.2cm !important;
				min-height: 1.2cm !important;
				line-height: 1.2cm !important;
			}

			.print-table td {
				border: 2px solid #000 !important;
				padding: 0 0.2cm !important;
				line-height: 1.2cm !important;
				vertical-align: middle !important;
				white-space: nowrap !important;
				overflow: hidden !important;
				text-overflow: ellipsis !important;
				text-align: center !important;
			}

			.dybox {
				padding: 10px !important;
				border: none !important;
			}

			.dybox-container {
				transform: none !important;
				width: 100% !important;
				height: auto !important;
				overflow: visible !important;
			}
		}

		.template5 .header-info {
			&>div:first-child {
				font-size: 1.5cm !important;
				margin-bottom: 0.8cm !important;
			}

			&>div:last-child {
				font-size: 1.1cm !important;
				margin-bottom: 0.5cm !important;
			}
		}

		.header-info:first-child {
			&>div:first-child {
				font-size: 1.6cm !important;
				font-weight: 600 !important;
				margin-bottom: 0.8cm !important;
			}

			&>div:last-child {
				font-size: 1.2cm !important;
				font-weight: 600 !important;
				margin-bottom: 0.5cm !important;
			}
		}

		.header-info:nth-child(2) {
			>div {
				font-size: 1.2cm !important;
				font-weight: 600 !important;
				line-height: 1.2 !important;
			}
		}

		.dybox-container {
			transform: none !important;
			width: 100% !important;
			height: auto !important;
			overflow: visible !important;
		}

		.dybox {
			width: 100% !important;
			height: auto !important;
			padding: 10px !important;
			border: none !important;
		}

		.pound-template .header-info {
			margin: 0 0 0.2cm 0 !important;
			line-height: 1.2 !important;
			font-size: 0.8cm !important;
		}

		.pound-template .header-info:first-child div:first-child {
			font-size: 1cm !important;
			margin-bottom: 0.1cm !important;
		}

		.pound-template .print-table {
			font-size: 0.8cm !important;
			font-weight: 600 !important;
			margin: 0 !important;
			width: 100% !important;
			border-collapse: collapse !important;
		}

		.pound-template .print-table tr {
			height: 1.2cm !important;
			min-height: 1.2cm !important;
			line-height: 1.2cm !important;
		}

		.template1 .print-table td,
		.template2 .print-table td,
		.template3 .print-table td,
		.template4 .print-table td,
		.template6 .print-table td {
			border: 2px solid #000 !important;
			padding: 0 0.2cm !important;
			line-height: 1.2cm !important;
			vertical-align: middle !important;
			white-space: nowrap !important;
			overflow: hidden !important;
			text-overflow: ellipsis !important;
			text-align: center !important;
		}

		// 模板7打印样式
		.template7 .header-info {
			&>div:first-child {
				font-size: 1.0cm !important;
				margin-bottom: 0.5cm !important;
			}

			&>div:last-child {
				font-size: 0.8cm !important;
				margin-bottom: 0.3cm !important;
			}
		}

		.template7 .header-info:nth-child(2)>div {
			font-size: 0.7cm !important;
			font-weight: 600 !important;
			line-height: 1.2 !important;
		}

		.template7 .print-table {
			font-size: 0.8cm !important;
			font-weight: 600 !important;
			margin: 0 !important;
			width: 100% !important;
			border-collapse: collapse !important;
			table-layout: fixed !important; // 锁定打印布局
		}

		// 打印列宽与预览保持一致
		.template7 .print-table tr td:nth-child(1) {
			width: 8% !important;
		}

		// 车号
		.template7 .print-table tr td:nth-child(2) {
			width: 35% !important;
		}

		// 货物名称
		.template7 .print-table tr td:nth-child(3) {
			width: 10% !important;
		}

		// 毛重
		.template7 .print-table tr td:nth-child(4) {
			width: 10% !important;
		}

		// 皮重
		.template7 .print-table tr td:nth-child(5) {
			width: 10% !important;
		}

		// 净重
		.template7 .print-table tr td:nth-child(6) {
			width: 17% !important;
		}

		// 结算量

		.template7 .print-table tr {
			height: 1.2cm !important; // 适当增加行高，容纳换行文字
			min-height: 1.2cm !important;
			line-height: 1.2cm !important;
		}

		.template7 .print-table td {
			border: 2px solid #000 !important;
			padding: 0 0.1cm !important; // 打印时减少内边距
			line-height: 1.2cm !important;
			vertical-align: middle !important;
			white-space: normal !important; // 允许打印时换行
			word-break: break-all !important; // 长货名拆分
			text-align: center !important;
			overflow: visible !important;
			text-overflow: clip !important;
		}

		.template1 .print-table,
		.template1 .print-table td,
		.template2 .print-table,
		.template2 .print-table td,
		.template3 .print-table,
		.template3 .print-table td,
		.template4 .print-table,
		.template4 .print-table td,
		.template5 .print-table,
		.template5 .print-table td,
		.template6 .print-table,
		.template6 .print-table td,
		.template7 .print-table,
		.template7 .print-table td {
			border: 2px solid #000 !important;
		}

		.el-dialog__footer,
		.pound-container,
		.el-pagination,
		.el-form,
		.el-card__header,
		::-webkit-scrollbar {
			display: none !important;
		}
	}
</style>
<style lang="scss" scoped>
	.pound-container {
		padding: 28px;
		box-sizing: border-box;
		position: relative;

		.pound-bottom {
			width: 100%;
			margin-top: 50px;
			max-height: 800px;
		}
	}
</style>